package com.example.finalhomework.cardgame

import android.Manifest
import android.content.pm.PackageManager
import android.net.Uri
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.navigation.NavController
import com.example.finalhomework.cardgame.ui.UserInfo
import com.example.finalhomework.cardgame.ui.saveUserInfo
import android.content.Context
import android.provider.MediaStore
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.core.content.FileProvider
import coil.compose.rememberImagePainter
import com.example.finalhomework.R
import java.io.File

@Composable
fun UpdateInfoScreen(
    navController: NavController,
    context: Context,
    userInfo: UserInfo, // 用户信息
    onSave: (UserInfo) -> Unit  // 保存用户信息的回调函数
) {
    // 打印接收到的参数
    Log.d(
        "UpdateInfoScreen",
        "Received parameters: name=${userInfo.name}, gender=${userInfo.gender}, studentId=${userInfo.studentId}, phone=${userInfo.phone}, email=${userInfo.email}, hobbies=${userInfo.hobbies}, avatarUri=${userInfo.avatarUri}"
    )

    val context = LocalContext.current  // 获取当前上下文
    var updatedUserInfo by remember { mutableStateOf(userInfo) }    // 更新后的用户信息

    // 获取保存的图片URI
    val savedImageUri = getSavedImageUri(context)
    if (savedImageUri != null) {    // 如果保存的图片URI不为空
        updatedUserInfo = updatedUserInfo.copy(avatarUri = savedImageUri.toString())    // 更新用户信息的头像URI
        Log.d("UpdateInfoScreen", "Loaded saved image URI: $savedImageUri")
    }

    var avatarUri by remember { mutableStateOf<Uri?>(null) }    // 头像URI
    var recomposeTrigger by remember { mutableStateOf(false) }  // 重组触发器
    var currentAvatarUri by remember { mutableStateOf(avatarUri ?: Uri.parse(updatedUserInfo.avatarUri)) }  // 当前头像URI

    // 打印当前头像URI
    Log.d("UpdateInfoScreen", "Initial currentAvatarUri: $currentAvatarUri")

    // 启动相机拍照
    val launcher = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { success ->
        if (success) {  // 如果拍照成功
            avatarUri?.let { uri ->
                Log.d("UpdateInfoScreen", "Photo taken, URI: $uri") // 打印拍照URI
                val bitmap = MediaStore.Images.Media.getBitmap(context.contentResolver, uri)    // 从URI获取位图
                val savedUri = saveBitmapToFile(context, bitmap, Uri.parse(updatedUserInfo.avatarUri))  // 将获取到的位图保存到文件中，并返回保存后的 URI
                Log.d("UpdateInfoScreen", "Photo saved, URI: $savedUri")    // 打印保存URI
                updatedUserInfo = updatedUserInfo.copy(avatarUri = savedUri.toString()) // 更新用户信息的头像URI
                currentAvatarUri = savedUri     // 更新当前头像URI
                recomposeTrigger = !recomposeTrigger // 触发重组
                onSave(updatedUserInfo) // 保存更新后的用户信息
                Log.d("UpdateInfoScreen", "Updated currentAvatarUri: $currentAvatarUri")
            }
        } else {
            Log.d("UpdateInfoScreen", "Photo taking failed")
        }
    }

    val showDialog = remember { mutableStateOf(false) } // 对话框显示状态

    // 请求存储权限
    val permissionLauncher = rememberLauncherForActivityResult( //用于启动权限请求活动结果
        contract = ActivityResultContracts.RequestMultiplePermissions() // 用合同请求多个权限
    ) { permissions ->
        val readPermissionGranted = permissions[Manifest.permission.READ_EXTERNAL_STORAGE] ?: false
        val writePermissionGranted = permissions[Manifest.permission.WRITE_EXTERNAL_STORAGE] ?: false
        if (!readPermissionGranted || !writePermissionGranted) {
            // 处理权限未授予的情况
            Log.d("UpdateInfoScreen", "Storage permissions not granted")
        }
    }

    // 检查并请求存储权限
    LaunchedEffect(Unit) {// 一旦启动，就会触发,unit表示没有特定的参数
        val readPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)  //检查是否已授予读取外部存储权限
        val writePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)    //检查是否已授予写入外部存储权限
        if (readPermission != PackageManager.PERMISSION_GRANTED || writePermission != PackageManager.PERMISSION_GRANTED) {
            permissionLauncher.launch(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE))   //请求权限
        }
    }

    // 使用Column布局来垂直排列组件
    Column(
        modifier = Modifier
            .fillMaxSize() // 填充整个屏幕
            .padding(16.dp) // 设置内边距
            .verticalScroll(rememberScrollState()), // 使内部内容可滚动
        horizontalAlignment = Alignment.CenterHorizontally // 水平居中对齐
    ) {
        // 使用Box布局来包裹头像图片和拍照按钮
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            contentAlignment = Alignment.Center
        ) {
            LaunchedEffect(recomposeTrigger) {
                // 当recomposeTrigger变化时触发重组
                Log.d("UpdateInfoScreen", "Recomposition triggered")
            }
            Image(
                painter = rememberImagePainter( // 从头像URI加载图片（rememberImagePainter创建并记住一个 ImagePainter，可以使用AsyncImage 组件来替代 rememberImagePainter ）
                    data = currentAvatarUri,
                    builder = {
                        crossfade(true)
                    }
                ),
                contentDescription = "Avatar",
                modifier = Modifier
                    .size(140.dp) // 设置图片大小
                    .clip(CircleShape) // 将图片裁剪为圆形
                    .border(2.dp, Color.Black, CircleShape), // 添加圆形边框
                contentScale = ContentScale.Crop // 确保图片填充整个圆形区域
            )

            // 拍照按钮
            IconButton(
                onClick = {
                    val file = File(context.filesDir, "avatar_${System.currentTimeMillis()}.png")   // 创建一个新文件
                    avatarUri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)    // 获取文件URI
                    Log.d("UpdateInfoScreen", "Launching camera with URI: $avatarUri")
                    launcher.launch(avatarUri)
                },
                modifier = Modifier.align(Alignment.BottomEnd).size(50.dp)
            ) {
                Icon(
                    painter = painterResource(id = R.drawable.baseline_photocamera),
                    contentDescription = "Change Avatar",
                    modifier = Modifier.size(40.dp)
                )
            }
        }

        // 使用Column布局来垂直排列用户信息输入框
        Column(modifier = Modifier.padding(16.dp)) {
            // 姓名输入框
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "Name: ",
                    modifier = Modifier.width(100.dp)
                )
                BasicTextField(
                    value = updatedUserInfo.name,
                    onValueChange = { updatedUserInfo = updatedUserInfo.copy(name = it) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 8.dp)
                        .background(Color.White)
                        .border(1.dp, Color.Black)
                        .padding(8.dp)
                )
            }

            // 学号输入框
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "Student ID: ",
                    modifier = Modifier.width(100.dp)
                )
                BasicTextField( // 基础文本输入框组件，允许用户输入和编辑文本
                    value = updatedUserInfo.studentId,  // 用户信息的学号
                    onValueChange = { updatedUserInfo = updatedUserInfo.copy(studentId = it) }, // 更新用户信息的学号
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 8.dp)
                        .background(Color.White)
                        .border(1.dp, Color.Black)
                        .padding(8.dp)
                )
            }

            // 电话号码输入框
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "Phone: ",
                    modifier = Modifier.width(100.dp)
                )
                BasicTextField(
                    value = updatedUserInfo.phone,
                    onValueChange = { updatedUserInfo = updatedUserInfo.copy(phone = it) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 8.dp)
                        .background(Color.White)
                        .border(1.dp, Color.Black)
                        .padding(8.dp)
                )
            }

            // 电子邮件输入框
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "Email: ",
                    modifier = Modifier.width(100.dp)
                )
                BasicTextField(
                    value = updatedUserInfo.email,
                    onValueChange = { updatedUserInfo = updatedUserInfo.copy(email = it) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 8.dp)
                        .background(Color.White)
                        .border(1.dp, Color.Black)
                        .padding(8.dp)
                )
            }

            // 性别选择
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "Gender: ",
                    modifier = Modifier.width(100.dp)
                )
                RadioButton(    // 单选按钮
                    selected = updatedUserInfo.gender == "Male",    // 选中状态
                    onClick = { updatedUserInfo = updatedUserInfo.copy(gender = "Male") }   // 点击时更新用户信息的性别
                )
                Text(text = "Male")
                Spacer(modifier = Modifier.width(16.dp))
                RadioButton(
                    selected = updatedUserInfo.gender == "Female",  // 选中状态
                    onClick = { updatedUserInfo = updatedUserInfo.copy(gender = "Female") } // 点击时更新用户信息的性别
                )
                Text(text = "Female")
            }

            // 爱好选择
            Text(
                text = "Hobbies:",
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(start = 8.dp)
                    .align(Alignment.Start)
            )
            Spacer(modifier = Modifier.height(8.dp))
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(start = 8.dp)
                    .background(Color.White)
                    .border(1.dp, Color.Black)
                    .padding(8.dp)
            ) {
                val hobbyOptions = listOf("Reading", "Music", "Hiking", "Photography")
                hobbyOptions.chunked(2).forEach { rowHobbies -> // 将爱好选项分组为两个一组
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        rowHobbies.forEach { hobby ->
                            Row(
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Checkbox(   // 复选框
                                    checked = updatedUserInfo.hobbies.contains(hobby),  // 选中状态
                                    onCheckedChange = { isChecked ->    // 根据选中状态更新 updatedUserInfo 对象中的爱好列表
                                        val hobbies = updatedUserInfo.hobbies.split(", ").toMutableList()
                                        if (isChecked) {
                                            hobbies.add(hobby)
                                        } else {
                                            hobbies.remove(hobby)
                                        }
                                        updatedUserInfo = updatedUserInfo.copy(hobbies = hobbies.joinToString(", "))    // 更新用户信息的爱好列表
                                    }
                                )
                                Text(text = hobby)
                            }
                        }
                    }
                }
            }

            Spacer(modifier = Modifier.height(16.dp))
            // 保存按钮
            Button(onClick = { showDialog.value = true }) {
                Text(text = "Save")
                Log.d("UpdateInfoScreen", "Save button clicked")
            }

            // 确认保存对话框
            if (showDialog.value) {
                AlertDialog(
                    onDismissRequest = { showDialog.value = false },
                    title = { Text(text = "Confirm Save") },
                    text = { Text(text = "Are you sure you want to save the information?") },
                    confirmButton = {
                        Button(onClick = {
                            showDialog.value = false
                            saveUserInfo(context, updatedUserInfo)
                            onSave(updatedUserInfo)
                            navController.navigate("PersonalInfo")
                            Log.d("UpdateInfoScreen", "Information saved and navigating to PersonalInfo")
                        }) {
                            Text("Yes")
                        }
                    },
                    dismissButton = {
                        Button(onClick = { showDialog.value = false }) {
                            Text("No")
                        }
                    }
                )
            }
        }
    }
}